import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/network/file_preview_http.dart';
import 'package:kq_flutter_core_widget/utils/file_preview_util.dart';
import 'package:kq_flutter_core_widget/utils/file_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_tv_widgets/config/kq_global.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../../resources/images.dart';
import '../../../resources/kq_theme_colors.dart';
import '../../../widgets/emptyView/empty_view.dart';
import '../../../widgets/progressbar/kq_horizontal_progress_bar.dart';
import '../file_preview/state.dart';

/// 文件预览半屏幕
///
/// 注意：仅支持在线文件预览，不要传本地文件路径
class FilePreviewHalfPage extends StatefulWidget {
  /// 文件名称，用文件后缀名来判断类型，如果没传自定义标题则显示文件名作为标题
  final String fileName;

  /// 文件url
  final String fileUrl;

  /// 自定义标题
  final String? customTitle;

  /// 关闭回调
  final Function(String fileName, String fileUrl)? onClose;

  const FilePreviewHalfPage(
      {super.key,
      required this.fileName,
      required this.fileUrl,
      this.onClose,
      this.customTitle});

  @override
  FilePreviewHalfPageState createState() => FilePreviewHalfPageState();
}

class FilePreviewHalfPageState extends State<FilePreviewHalfPage> {
  final WebViewController webController = WebViewController();

  /// 文件预览状态
  FilePreviewStatus status = FilePreviewStatus.loading;

  /// 进度条进度值
  double _progress = 0;

  /// 是否使用WebView
  bool useWebView = false;

  /// 是否文本
  bool isTxt = false;

  /// 是否图片
  bool isImg = false;

  /// 是否显示进度条
  bool showProgress = false;

  /// txt内容
  String txtContent = '';

  /// img路径
  String imgPath = '';

  @override
  void initState() {
    super.initState();
    reload();
  }

  @override
  void didUpdateWidget(covariant FilePreviewHalfPage oldWidget) {
    if (oldWidget.fileUrl != widget.fileUrl) {
      reload();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: KqThemeColors.bgDark,
      child: Stack(
        children: [
          Column(
            children: [
              Container(
                height: 64.r,
                padding: EdgeInsets.symmetric(horizontal: 24.r),
                color: KqThemeColors.bgDefault,
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        widget.customTitle ?? widget.fileName ?? '',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 24.sp, color: KqThemeColors.textBlack85),
                      ),
                    ),
                    KqInkWell(
                      onTap: () {
                        widget.onClose?.call(widget.fileName, widget.fileUrl);
                      },
                      radius: 60.r,
                      verticalPadding: 15.r,
                      horizontalPadding: 15.r,
                      child: Image.asset(
                        Images.commonIcGuanbi,
                        width: 24.r,
                        height: 24.r,
                        fit: BoxFit.fill,
                        package: KqGlobal.packageName,
                      ),
                    ),
                  ],
                ),
              ),
              //顶部进度条视图
              Visibility(
                  visible: showProgress,
                  child: KqHorizontalProgressBar(
                    progress: _progress,
                    pbColor: KqThemeColors.bgBlue,
                    height: 8.r,
                  )),
              //文件加载失败视图
              Visibility(
                  visible: status == FilePreviewStatus.failed,
                  child: const Expanded(
                    child: KqEmptyView(
                      text: '文件加载失败',
                    ),
                  )),
              //文件不支持类型视图
              Visibility(
                  visible: status == FilePreviewStatus.notSupport,
                  child: const Expanded(
                    child: KqEmptyView(
                      text: '不支持预览的文件类型',
                    ),
                  )),
              //加载中视图
              Visibility(
                  visible: status == FilePreviewStatus.loading,
                  child: Expanded(
                    child: Container(
                      alignment: Alignment.center,
                      child: SizedBox(
                        width: 150.r,
                        height: 150.r,
                        child: const CircularProgressIndicator(),
                      ),
                    ),
                  )),
              //img视图
              Visibility(
                  visible: !useWebView &&
                      isImg &&
                      status == FilePreviewStatus.success,
                  child: Expanded(
                    child: KqImage.file(
                      url: imgPath,
                      fit: BoxFit.contain,
                      errorImage: Images.commonPicQuesheng1024,
                      placeHolder: Images.commonPicQuesheng1024,
                      package: KqGlobal.packageName,
                    ),
                  )),
              //txt视图
              Visibility(
                  visible: !useWebView &&
                      isTxt &&
                      status == FilePreviewStatus.success,
                  child: Expanded(
                    child: SingleChildScrollView(
                        child: Padding(
                      padding: EdgeInsets.all(20.r),
                      child: Text(
                        txtContent,
                        style: TextStyle(
                            fontSize: 24.sp, color: KqThemeColors.text26),
                      ),
                    )),
                  )),
              //浏览器视图
              Visibility(
                visible: useWebView && status == FilePreviewStatus.success,
                child: Expanded(
                    child: WebViewWidget(
                  controller: webController,
                )),
              )
            ],
          ),
          Positioned(
            right: 20.r,
            top: 84.r,
            child: KqInkWell(
              horizontalPadding: 10.r,
              verticalPadding: 10.r,
              radius: 4.r,
              onTap: () {
                FilePreviewUtil.previewFile(
                    url: widget.fileUrl,
                    fileName: widget.fileName,
                    customTitle: widget.customTitle);
              },
              child: Image.asset(
                Images.commonIcQuanping,
                width: 50.r,
                height: 50.r,
                fit: BoxFit.fill,
                package: KqGlobal.packageName,
              ),
            ),
          )
        ],
      ),
    );
  }

  reload() async {
    setState(() {
      isImg = false;
      isTxt = false;
      status = FilePreviewStatus.loading;
    });
    String fileName = widget.fileName ?? '';
    String url = widget.fileUrl ?? '';
    if (canOpenWithWps(fileName)) {
      var wpsUrl = await FilePreviewHttp.getWpsUrl(url, fileName);
      if (wpsUrl != null) {
        setState(() {
          status = FilePreviewStatus.success;
          useWebView = true;
        });
        load(wpsUrl);
      } else {
        setState(() {
          status = FilePreviewStatus.failed;
        });
      }
    } else if (FilePreviewUtil.isImage(fileName)) {
      //图片文件处理
      var dir = await FileUtil.getTempDownloadPath();
      var filePath = await FilePreviewHttp.downloadFile(url, dir, fileName,
          (count, total) {
        setState(() {
          showProgress = true;
          _progress = count * 100.0 / total;
        });
      });
      showProgress = false;
      if (filePath != null) {
        //下载成功
        setState(() {
          imgPath = filePath;
          isImg = true;
          status = FilePreviewStatus.success;
        });
      } else {
        //下载失败
        setState(() {
          status = FilePreviewStatus.failed;
        });
      }
    } else if (isTxtFile(fileName)) {
      //下载下来本地处理，比如txt
      var dir = await FileUtil.getTempDownloadPath();
      var filePath = await FilePreviewHttp.downloadFile(url, dir, fileName,
          (count, total) {
        setState(() {
          showProgress = true;
          _progress = count * 100.0 / total;
        });
      });
      showProgress = false;
      if (filePath != null) {
        //下载成功
        var string = await FileUtil.readFileAsString(filePath);
        setState(() {
          txtContent = string;
          isTxt = true;
          status = FilePreviewStatus.success;
        });
      } else {
        //下载失败
        setState(() {
          status = FilePreviewStatus.failed;
        });
      }
    } else {
      //不支持的打开的文件
      setState(() {
        status = FilePreviewStatus.notSupport;
      });
    }
  }

  /// 是不是纯文本文件
  bool isTxtFile(String fileName) {
    return fileName.toLowerCase().endsWith(".txt") ||
        fileName.toLowerCase().endsWith(".json") ||
        fileName.toLowerCase().endsWith(".html") ||
        fileName.toLowerCase().endsWith(".java") ||
        fileName.toLowerCase().endsWith(".xml");
  }

  /// 是不是pdf文件
  bool isPdfFile(String fileName) {
    return fileName.toLowerCase().endsWith(".pdf");
  }

  /// 能否用wps打包
  bool canOpenWithWps(String fileName) {
    return fileName.toLowerCase().endsWith(".xls") ||
        fileName.toLowerCase().endsWith(".xlsx") ||
        fileName.toLowerCase().endsWith(".pdf") ||
        fileName.toLowerCase().endsWith(".doc") ||
        fileName.toLowerCase().endsWith(".docx") ||
        fileName.toLowerCase().endsWith(".csv") ||
        fileName.toLowerCase().endsWith(".pptx") ||
        fileName.toLowerCase().endsWith(".ppt");
  }

  load(String url, {bool? isLoadHTMLString}) {
    var web = webController
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            _progress = progress.toDouble();
            setState(() {});
          },
          onPageStarted: (String url) {
            showProgress = true;
            setState(() {});
          },
          onPageFinished: (String url) {
            showProgress = false;
            status = FilePreviewStatus.success;
            setState(() {});
          },
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      );
    if (isLoadHTMLString != null && isLoadHTMLString == true) {
      web.loadHtmlString(url);
    } else {
      web.loadRequest(url.contains('http://') || url.contains('https://')
          ? Uri.parse(url)
          : Uri.file(url));
    }
  }
}
